<template>
  <q-layout view="hHh lpR fFf">
    <!-- 消息显示区域 -->
    <q-page-container>
      <q-page class="messages-container">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.sender_id === userId ? 'sent' : 'received']"
        >
          <span>{{ msg.content }}</span>
        </div>
      </q-page>
    </q-page-container>

    <!-- 输入区域 -->
    <q-footer class="input-container">
      <q-input
        v-model="message"
        placeholder="Type a message"
        @keyup.enter="handleSendMessage"
        outlined
        dense
        class="q-mr-sm"
      />
      <q-btn label="Send" color="primary" @click="handleSendMessage" />
    </q-footer>
  </q-layout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { connectWebSocket, sendMessage, closeWebSocket } from 'src/utils/websocket';

// 用户 ID 和接收者 ID 示例值
const userId = 7;
const receiverId = 1;

// 定义消息内容和消息列表
const message = ref('');
const messages = ref([]);

// 处理接收到的消息
const handleReceiveMessage = (msg) => {
  messages.value.push({
    sender_id: msg.sender_id,
    content: msg.content,
  });
};

// 发送消息
const handleSendMessage = () => {
  if (message.value.trim()) {
    const msg = {
      sender_id: userId,
      content: message.value.trim(),
      timestamp: Date.now() // 添加时间戳
    };
    sendMessage(JSON.stringify(msg))
    messages.value.push(msg);
    message.value = '';
  }
};

// 连接 WebSocket
onMounted(() => {
  connectWebSocket(userId, receiverId, handleReceiveMessage);
});

// 断开 WebSocket 连接
onBeforeUnmount(() => {
  closeWebSocket();
});
</script>

<style scoped>
.messages-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow-y: auto;
  padding: 16px;
  background-color: #f0f2f5;
}

.message {
  padding: 8px 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  max-width: 70%;
}

.sent {
  align-self: flex-end;
  background-color: #bae7ff;
}

.received {
  align-self: flex-start;
  background-color: #ffccc7;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background-color: white;
}
</style>
